package com.weitu.hiddenDanger.controller;


import com.alibaba.fastjson.JSONArray;
import com.weitu.accessory.bean.AccessoryPackageInfo;
import com.weitu.accessory.service.AccessoryUtilService;
import com.weitu.accessory.util.AccessoryUtil;
import com.weitu.base.controller.BaseController;
import com.weitu.hiddenDanger.entity.HiddenDangerInfo;
import com.weitu.hiddenDanger.service.HDPrecautionService;
import com.weitu.hiddenDanger.service.HDRegisterService;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.user.entity.User;
import com.weitu.plugin.PageView;
import com.weitu.util.AjaxResult;
import com.weitu.util.IDGenerator;
import com.weitu.workflow.flowBusiness.constant.FlowBusinessConstants;
import com.weitu.workflow.flowManagement.entity.WorkflowReview;
import com.weitu.workflow.flowManagement.service.FlowManagementService;
import org.fireflow.engine.IProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * Created by fanyuting on 2017/3/31 0031.
 * 隐患登记controller
 */
@Controller
@RequestMapping("hiddenDanger/hdRegister")
public class HDRegisterController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "hiddenDanger/hdRegister/";
    @Autowired
    private AccessoryUtilService accessoryUtilService;//附件
    @Autowired
    private HDRegisterService hdRegisterService;//隐患登记信息
    @Autowired
    private HDPrecautionService hdPrecautionService;//防范措施

    @Autowired
    private FlowManagementService flowManagementService;//流程管理service
    private WorkflowReview workflowReview;

    public WorkflowReview getWorkflowReview() {
        return workflowReview;
    }

    public void setWorkflowReview(WorkflowReview workflowReview) {
        this.workflowReview = workflowReview;
    }


    /**
     * 跳转到隐患登记列表页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String toHDRegistPage(Model model) {

        return MODULE_BATH_PATH + "list";

    }

    /**
     * 查询分页列表数据
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryListByParam")
    public Object queryList(HttpServletRequest request) {

        Map<String, Object> map = new HashMap<String, Object>();
        //获取前台参数
        putParametersIntoMap(map);
        Integer totalNum = hdRegisterService.queryListCount(map);//获取总数
        DataGridPagination pagination = DataGridPagination.getInstance(request, totalNum);
        PageView pageView = pagination.getPageView();//生成pageView分页对象
        map.put("pageView", pageView);
        List<HiddenDangerInfo> list = hdRegisterService.queryList(map);
        return pagination.flushDataGridData(list);
    }

    /**
     * 跳转到隐患登记页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String toHDAddPage(Model model) {
        User loginUser = getSessionUser();
        //String businessId = "123abc";//业务Id
        //查询该业务对应的附件信息
        // List<AccessoryPackageInfo> accessoryList =  accessoryUtilService.queryAccessoryByBusinessId(businessId);
        //model.addAttribute("accessoryList",accessoryList);
        model.addAttribute("uploadUserId", loginUser.getId());
        //model.addAttribute("businessId","123456abcd");
        return MODULE_BATH_PATH + "add";
    }

    /**
     * 保存隐患信息
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @Transactional
    public AjaxResult addHD(HttpServletRequest request, HttpServletResponse response) {


        Map<String, Object> map = new HashMap<String, Object>();
        getAddBasicFieldMap(map);
        boolean hdFlag = false;
        boolean accFlag = false;
        boolean preFlag = false;
        //保存附件登记信息
        hdFlag = hdRegisterService.addHDRegisterInfo(map);
        //保存隐患登记信息
        if (hdFlag) {
            accFlag = AccessoryUtil.saveAccerssoryInfo(map.get("id").toString());
        }
        //保存隐患防范措施
        if (hdFlag) {
            preFlag = addPrecaution(map);
        }

        if (accFlag && preFlag) {
            return success("隐患信息登记成功！");
        }
        return fail("隐患信息登记失败！");
    }

    /**
     * 跳转到隐患登记编辑页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String toHDEditPage(Model model, HttpServletRequest request) {
        User loginUser = getSessionUser();
        String businessId = request.getParameter("businessId");//业务Id
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", businessId);
        //查询隐患信息
        List<HiddenDangerInfo> hdList = this.hdRegisterService.queryHDRegisterInfoById(map);
        //查询该业务对应的附件信息
        List<AccessoryPackageInfo> accessoryList = accessoryUtilService.queryAccessoryByBusinessId(businessId);
        model.addAttribute("hdInfo", hdList.get(0));
        model.addAttribute("accessoryList", accessoryList);
        model.addAttribute("uploadUserId", loginUser.getId());
        //model.addAttribute("businessId","123456abcd");
        return MODULE_BATH_PATH + "edit";
    }

    /**
     * 跳转到隐患登记详情页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String toHDDetailPage(Model model, HttpServletRequest request) {
        User loginUser = getSessionUser();
        String businessId = request.getParameter("businessId");//业务Id
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", businessId);
        //查询隐患信息
        List<HiddenDangerInfo> hdList = this.hdRegisterService.queryHDRegisterInfoById(map);
        //查询该业务对应的附件信息
        List<AccessoryPackageInfo> accessoryList = accessoryUtilService.queryAccessoryByBusinessId(businessId);
        model.addAttribute("hdInfo", hdList.get(0));
        model.addAttribute("accessoryList", accessoryList);
        model.addAttribute("uploadUserId", loginUser.getId());
        //model.addAttribute("businessId","123456abcd");
        return MODULE_BATH_PATH + "detail";
    }

    /**
     * 保存编辑的隐患信息
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public AjaxResult editHD(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        getEditBasicFieldMap(map);
        boolean hdFlag = false;
        boolean accFlag = false;
        boolean preFlag = false;
        hdFlag = hdRegisterService.editHDRegisterInfo(map);
        //保存附件登记信息
        if (hdFlag) {
            accFlag = AccessoryUtil.saveAccerssoryInfo(map.get("id").toString());
        }
        if (hdFlag) {
            preFlag = editPrecaution(map);
        }
        if (accFlag && preFlag) {
            return success("隐患登记信息更新成功！");
        }
        return fail("隐患登记信息更新失败！");
    }

    /**
     * 删除隐患信息
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @Transactional
    public AjaxResult deleteHD(HttpServletRequest request, HttpServletResponse response) {

        String businessId = request.getParameter("businessId");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", businessId);
        boolean hdFlag = false;
        hdFlag = hdRegisterService.deleteHDRegisterInfo(map);
        if (hdFlag) {
            return success("隐患登记信息删除成功！");
        }
        return fail("隐患登记信息删除失败！");
    }

    /**
     * 查询防范措施分页列表数据
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryPrecautionList", method = RequestMethod.POST)
    @Transactional
    public Object queryPrecautionList(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        //获取前台参数
        putParametersIntoMap(map);
        Integer totalNum = hdPrecautionService.queryPrecautionCount(map);//获取总数
        DataGridPagination pagination = DataGridPagination.getInstance(request, totalNum);
        PageView pageView = pagination.getPageView();//生成pageView分页对象
        map.put("pageView", pageView);
        List<Map<String, Object>> list = hdPrecautionService.queryPrecautionList(map);
        return pagination.flushDataGridData(list);

    }

    /**
     * 保存隐患防范措施信息方法
     *
     * @return
     */
    public boolean addPrecaution(Map<String, Object> map) {
        String hdId = map.get("id").toString();
        String addTime = map.get("addTime").toString();
        String addUserId = map.get("addUserId").toString();
        String addDeptId = map.get("addDeptId").toString();
        //列表数据
        String dataStr = null;
        boolean flag = false;
        if (map.get("precautionData") != null) {
            dataStr = map.get("precautionData").toString();
            //将json字符串转为list对象
            List<Map> list = JSONArray.parseArray(dataStr, Map.class);
            //List<Precaution> list = JSONArray.parseArray(dataStr,Precaution.class);
            //将业务id、添加人、添加时间等信息放入对象中
            if (list.size() > 0) {
                for (Map m : list) {
                    String uuid = IDGenerator.getId();
                    //dutyUserName的值为dutyUserId
                    // m.put("dutyUserId",m.get("dutyUserName"));
                    m.put("id", uuid);
                    m.put("hdId", hdId);
                    m.put("addUserId", addUserId);
                    m.put("addDeptId", addDeptId);
                }

                map.put("addList", list);
                flag = hdPrecautionService.addPrecaution(map);
            } else {
                flag = true;
            }

        }

        //Map<String,Object> map = new HashMap<String,Object>();
        // getAddBasicFieldMap(map);
        //保存隐患防范措施信息
        //boolean flag  = hdPrecautionService.addPrecaution(map);
        return flag;
    }

    /**
     * 编辑防范措施列表
     *
     * @return
     */
    public boolean editPrecaution(Map<String, Object> map) {
        String hdId = map.get("id").toString();
        String addTime = map.get("updateTime").toString();
        String addUserId = map.get("updateUserId").toString();
        String addDeptId = map.get("updateDeptId").toString();
        //列表数据
        String dataStr = null;
        boolean addFlag = false;
        boolean editFlag = false;
        if (map.get("precautionData") != null) {
            dataStr = map.get("precautionData").toString();
            //将json字符串转为list对象
            List<Map> list = JSONArray.parseArray(dataStr, Map.class);
            //List<Precaution> list = JSONArray.parseArray(dataStr,Precaution.class);
            //区分新增和编辑列表
            List<Map> addList = new ArrayList<Map>();
            List<Map> editList = new ArrayList<Map>();
            //将业务id、添加人、添加时间等信息放入对象中
            for (Map m : list) {

                //dutyUserName的值为dutyUserId
                // m.put("dutyUserId",m.get("dutyUserName"));


                //编辑列表
                if (m.get("id") != null && !"".equals(m.get("id"))) {
                    editList.add(m);
                } else {
                    String uuid = IDGenerator.getId();
                    m.put("id", uuid);
                    addList.add(m);
                    m.put("hdId", hdId);
                    m.put("addUserId", addUserId);
                    m.put("addDeptId", addDeptId);
                }
            }
            if (addList.size() > 0) {
                map.put("addList", addList);
                addFlag = hdPrecautionService.addPrecaution(map);
            } else {
                addFlag = true;
            }
            if (editList.size() > 0) {
                map.put("editList", editList);
                editFlag = hdPrecautionService.editPrecaution(map);
            } else {
                editFlag = true;
            }

        }
        //删除隐患防范措施
        if (map.get("precautionDelIds") != null) {
            String precautionDelIds = map.get("precautionDelIds").toString();
            String[] ids = precautionDelIds.split(",");
            Map<String, Object> preMap = new HashMap<String, Object>();
            preMap.put("ids", ids);
            this.hdPrecautionService.deletePrecaution(preMap);

        }


        //Map<String,Object> map = new HashMap<String,Object>();
        // getAddBasicFieldMap(map);
        //保存隐患防范措施信息
        //boolean flag  = hdPrecautionService.addPrecaution(map);
        return addFlag && editFlag;
    }
    /*==============业务审批流程相关controller=======================*/

    /**
     * 提交隐患登记信息审批
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "submitHDRegisterApplication", method = RequestMethod.POST)
    public AjaxResult submitHDRegisterApplication(HttpServletRequest request) throws Exception {
        User crrentUser = this.getSessionUser();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        AjaxResult result = new AjaxResult();

        putParametersIntoMap(paramMap);

        String hdRegisterApplicationId = paramMap.get("id").toString();//请假单id
        String nextUserId = paramMap.get("nextUserId").toString();//下一环节审批人id
        //获取请假单信息
        List<HiddenDangerInfo> hdInfos = this.hdRegisterService.queryHDRegisterInfoById(paramMap);
        HiddenDangerInfo hdInfo = hdInfos.get(0);//1042959b993b4380893b9e624c16aeba
        // LeaveApplication leaveApplication=this.leaveApplicationService.queryLeaveApplicationInfoById(leaveApplicationId);
        //启动流程实例
        IProcessInstance processInstance = this.flowManagementService.flowCreateAndRun(FlowBusinessConstants.BUSINESS_HDREGISTERAPPLICATION, hdRegisterApplicationId, "业务描述信息", nextUserId);
        //int i=1/0;
        boolean appStateFlag = false;
        if (processInstance != null) {
            appStateFlag = this.hdRegisterService.editHDRegisterAppState(hdRegisterApplicationId, "0");
        }

        if (appStateFlag) {
            result.setMessage("提交成功！");
            result.setSuccess(true);
        } else {
            result.setMessage("提交失败！");
            result.setSuccess(false);
        }
        return result;
    }

    /***
     * 跳转到隐患登记信息审批页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toHDRegisterApplicationVerify")
    public ModelAndView toHDRegisterApplicationVerify(HttpServletRequest request) {
        User crrentUser = this.getSessionUser();
        ModelAndView modelAndView = new ModelAndView();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //获取参数
        putParametersIntoMap(paramMap);
        String businessId = paramMap.get("businessId").toString();//获取业务id，以businessId命名
        //工作项id
        String workItemId = paramMap.get("workItemId").toString();
        //表单类型；0：只读表单；1：编辑表单
        int formType = paramMap.get("formType") != null ? Integer.parseInt(paramMap.get("formType").toString()) : 0;
        modelAndView.addObject("workItemId", workItemId);
        modelAndView.addObject("formType", formType);

        //获取意见信息
        WorkflowReview workflowReview = this.flowManagementService.queryWorkflowReviewByWorkItemId(workItemId);
        modelAndView.addObject("workflowReview", workflowReview);

        //查询隐患信息
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", businessId);
        List<HiddenDangerInfo> hdList = this.hdRegisterService.queryHDRegisterInfoById(map);
        //查询该业务对应的附件信息
        List<AccessoryPackageInfo> accessoryList = accessoryUtilService.queryAccessoryByBusinessId(businessId);
        modelAndView.addObject("hdInfo", hdList.get(0));
        modelAndView.addObject("accessoryList", accessoryList);
        modelAndView.addObject("uploadUserId", crrentUser.getId());
        //步骤：第几步信息
        String step = request.getParameter("step");
        modelAndView.addObject("step", step);
        modelAndView.setViewName(MODULE_BATH_PATH + "verify");
        return modelAndView;
    }

    /**
     * 审批隐患登记信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "verifyHDRegisterApplication")
    public AjaxResult verifyHDRegisterApplication(HttpServletRequest request) throws Exception {
        String businessId = request.getParameter("businessId");
        String workItemId = request.getParameter("workItemId");//获取工作项id
        //查询处理结果及意见
        WorkflowReview workflowReview = this.flowManagementService.getWorkflowReviewByRequest(request, "workflowReview", workItemId);
        //保存处理结果
        boolean boo = this.flowManagementService.saveWorkflowReview(workflowReview);
        //步骤：第几步信息
        String step = request.getParameter("step");
        //结束环节，继续流程向下执行
        if (boo) {
            //更改业务中的审批状态
            String result = workflowReview.getResult();
            if ("1".equals(result)) {
                if ("2".equals(step)) {
                    this.hdRegisterService.editHDRegisterAppState(businessId, "1");
                }
            } else {
                if ("2".equals(step)) {
                    this.hdRegisterService.editHDRegisterAppState(businessId, "-1");
                }
            }
            this.flowManagementService.workItemComplete(workItemId);
        }
        System.out.println(workflowReview.getComments());

        AjaxResult result = new AjaxResult();
        if (boo) {
            result.setMessage("提交成功！");
            result.setSuccess(true);
        } else {
            result.setMessage("提交失败！");
            result.setSuccess(false);
        }
        return result;
    }
}
